package com.xc.common.tool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class ApiSignature {
	
	protected static final Logger logger = LoggerFactory.getLogger(ApiSignature.class);

	/**
	 * 判断接口签名
	 * 根据参数名称（除签名和图片）将所有请求参数按照字母先后顺序排序:key + value .... key + value
                      例如：将foo=1,bar=2,baz=3 排序为bar=2,baz=3,foo=1，参数名和参数值链接后，得到拼装字符串bar2baz3foo1 系统支持MD5加密方式:
       md5：将secret 拼接到参数字符串头、尾进行md5加密后，再转化成大写，格式是：byte2hex(md5(secretkey1value1key2value2...secret))
	 * @param paramMap
	 * @param appSecret
	 * @param sign
	 * @return
	 */
	public static boolean  checkSignature(Map<String, String[]> paramMap,String appSecret,String sign)
	{
		if(paramMap!=null&&StringUtils.isNotBlank(appSecret)&&StringUtils.isNotBlank(sign))
		{
			logger.debug("appSecret="+appSecret+",from_sign="+sign);
			StringBuffer content = new StringBuffer();
			content.append(appSecret);
			
			List<String> keys = new ArrayList<String>(paramMap.keySet());
			keys.remove("sign");
			Collections.sort(keys);
			for (int i = 0; i < keys.size(); i++) {
	            String key = keys.get(i);
	            String[] value = paramMap.get(key);
	            for(int j=0;j<value.length;j++)
	            {
	            	content.append(key+value[j]);
	            }
	        } 
			content.append(appSecret);
			logger.debug(content.toString());
	
			String toSign=YYMD5.hashToHexString(content.toString());
			logger.debug("toSign="+toSign);
			
			if(sign.equals(toSign))
			{
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 获取签名
	 *  根据参数名称（除签名和图片）将所有请求参数按照字母先后顺序排序:key + value .... key + value
                      例如：将foo=1,bar=2,baz=3 排序为bar=2,baz=3,foo=1，参数名和参数值链接后，得到拼装字符串bar2baz3foo1 系统支持MD5加密方式:
       md5：将secret 拼接到参数字符串头、尾进行md5加密后，再转化成大写，格式是：byte2hex(md5(secretkey1value1key2value2...secret))
	 * @param paramMap
	 * @param appSecret
	 * @return
	 */
	public static String  makeSignature(Map<String, Object> paramMap,String appSecret)
	{
		if(paramMap!=null&&StringUtils.isNotBlank(appSecret))
		{
			StringBuffer content = new StringBuffer();
			content.append(appSecret);
			
			List<String> keys = new ArrayList<String>(paramMap.keySet());
			keys.remove("sign");
			Collections.sort(keys);
//			System.out.println("参数=============：");
			for (int i = 0; i < keys.size(); i++) {
	            String key = keys.get(i);
	            Object value = paramMap.get(key);
	            content.append(key+value.toString()); 
//	            System.out.println(key + " :  " + value);
	        } 
			content.append(appSecret);
			logger.debug(content.toString());
//			System.out.println("拼装字符串： "+content.toString());
			String toSign=YYMD5.hashToHexString(content.toString());
			logger.debug("toSign="+toSign);
			return toSign;
		}
		
		return "";
	}
	public static void main(String[] args) {
//		List<SysUserEntity> list = new ArrayList<>();
//		SysUserEntity u = new SysUserEntity();
//		u.setName("张峰");
//		u.setAddress("11233");
//		list.add(u);
//		Map<String,Object> params = new HashMap<>();
//		params.put("timestamp","1123");
//		params.put("machineNo","zlyy");
//		params.put("accessToken","msb5cM+qaFNeDe6DxLXvkQ==");
//		params.put("data",list);
//		String serverSign = ApiSignature.makeSignature(params, Constant.SECRETKEY);
//		System.out.println(serverSign);
		
		
		String a = "000201078cdb4acf81b32560820dd9c6accessToken+/K2OWqO6exvpg03gqepIw==adviceIdadviceNameapplyTime2022-03-29 15:41:20attendancebeginTime2022-03-29 15:41:20codecontachUserIdcontachUserNamecontachUserTelcreateUserId1createUserNametopadminendTime2022-03-29 16:41:20id1508710885613506560layTableCheckboxonmachineNozlyymeetingState1module1nodeOrgId1581630917787652105nodeOrgId_select_input原料药车间nodeOrgId_select_nodeId1581630917787652105orgId1placeId1470571229147697152placeName行政办公楼一楼会议室AplayMoment30powerAfter30powerBefore30realEndTime2022-03-29 16:41:20signNum0state3timestamp1648539697969topic1111triggerMoment1000201078cdb4acf81b32560820dd9c6";
		System.out.println(YYMD5.hashToHexString(a));
	}
}
